<?php
class PsytestController extends CController {
	public function filters() {
		return array(
				'accessControl'
		);
	}

	public function accessRules() {
		return array(
			array(
				'allow',
				'expression' => ForumMembers::isAdmin()
			),
			array(
				'deny',
			),
		);
	}
	
	public function actionIndex() {
		$criteria = new CDbCriteria;
        $criteria->order = 'topicId DESC';
		$psyTestsCount = TestTopics::model()->count($criteria);
		// Pagination
		$pages = new CPagination($psyTestsCount);
		$pages->pageSize = Yii::app()->params['manageListPerPage'];
		$pages->applyLimit($criteria);
		
		$topics = TestTopics::model()->findAll($criteria);
		$this->render('index', array(
				'topics' => $topics,
				'pages' => $pages
			)
		);
	}
	
    public function actionEditrecommendpsytest() {
		$optionName = 'recommendPsytest';
		$option = Options::model()->findOptionByName($optionName);
		if(isPost()) {
			$option->optionValue = $_POST[$optionName];
			if($option->save()) {
			}
		}
		$recommendPsytests = explode(',', $option->optionValue);
		$topics = TestTopics::model()->findAllByPk($recommendPsytests);

		$this->render('edit-recommendpsytest', array('topics' => $topics, 'recommendPsytests' => $recommendPsytests, 'option' => $option));
    }

	public function actionNewtopic() {
		$topic = new TestTopics;
        $categories = TestCategories::model()->findAll();
		
		$this->render('new-topic', array(
				'topic' => $topic,
                'categories' => $categories
			)
		);
	}
	
	public function actionAddtopic() {
		if(isset($_POST) && isset($_POST['TestTopics'])) {
            $topic = new TestTopics;
            $topic->topicStatus = TestTopics::STATUS_UNPUBLISHED;
            $topic->setAttribute('topicTitle', $_POST['TestTopics']['topicTitle']);
            $topic->setAttribute('metaKey', $_POST['TestTopics']['metaKey']);
            $topic->setAttribute('metaDescr', $_POST['TestTopics']['metaDescr']);
            $topic->setAttribute('topicType', $_POST['TestTopics']['topicType']);
            $topic->setAttribute('psyTestCategoryId', (int)$_POST['TestTopics']['psyTestCategoryId']);
            $topic->setAttribute('hasSecDim', (int)$_POST['TestTopics']['hasSecDim']);
            $topic->setAttribute('topicDescr', $_POST['TestTopics']['topicDescr']);
            $topic->createdAt = time();
            if(is_uploaded_file($_FILES['TestTopics']['tmp_name']['topicImage'])) {
               	$topic->topicImage = CUploadedFile::getInstance($topic, 'topicImage');
            }
            if($topic->save()) {
                if($topic->topicImage instanceof CUploadedFile) {
                	$tempPath = tempnam(UPLOADS_TEMP, 'ti_');
                	$topic->topicImage->saveAs($tempPath, true);
                	$this->processImage($topic, $tempPath);
                }
                Yii::app()->user->setFlash('successMessage', '心理测试主题添加成功。');
            	$this->redirect(array('/admin/psytest/edittopic', 'id' => $topic->topicId));
            } else {
                Yii::app()->user->setFlash('errorTopic', serialize($topic));
            	$this->redirect(array('/admin/psytest/newtopic'));
            }
        }
	}
	
	public function actionEdittopic() {
		$topic = $this->loadTestTopic();
        $criteria = new CDbCriteria;
        $criteria->condition = 'topicId = '.$topic->topicId;
        $conclusionsCount = TestConclusions::model()->count($criteria);
        $dims = TestDimens::model()->findAll($criteria);
        $categories = TestCategories::model()->findAll();
        
		$this->render('edit-topic', array(
                'topic' => $topic, 
                'dims' => $dims, 
                'conclusionsCount' => $conclusionsCount,
                'categories' => $categories
            )
        );
	}
	
    public function actionEditanswerlinkage() {
        $linkageId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($linkageId !== null) {
            $linkage = TestAnswerLinkage::model()->findByPk($linkageId);

            if($linkage !== null) {
                $questions = $this->loadQuestions($linkage->answer->question->topic->topicId);
                $questionsListData = $this->getQuestionsListDataWithOrder($questions);
                $conclusions = $this->loadConclusions($linkage->answer->question->topic->topicId);

                $this->render('edit-answerlinkage', array(
                        'linkage' => $linkage, 
                        'questions' => $questions,
                        'conclusions' => $conclusions,
                        'questionsListData' => $questionsListData
                    )
                );
            }
        }
    }

    public function actionUpdateanswerlinkage() {
        if(isset($_POST) && isset($_POST['TestAnswerLinkage'])) {
            $linkage = TestAnswerLinkage::model()->findByPk((int)$_POST['TestAnswerLinkage']['linkageId']);
            if($linkage !== null) {
                $linkage->attributes = $_POST['TestAnswerLinkage'];
                $linkage->linkToId = isset($_POST['TestAnswerLinkage']['linkToId']) ? $_POST['TestAnswerLinkage']['linkToId'] : null;
                if($linkage->save()) {
                    Yii::app()->user->setFlash('successMessage', '心理测试主题更新成功。');
                } else {
                    Yii::app()->user->setFlash('errorLinkage', serialize($linkage));
                }
                $this->redirect(array('admin/psytest/editanswerlinkage', 'id' => $linkage->linkageId));
            }
        }
    }

	public function actionUpdatetopic() {
        if(isset($_POST) && isset($_POST['TestTopics'])) {
            $topic = TestTopics::model()->findByPk((int)$_POST['TestTopics']['topicId']);
            if($topic !== null) {
                $topic->setAttribute('topicStatus', $_POST['TestTopics']['topicStatus']);
                $topic->setAttribute('topicTitle', $_POST['TestTopics']['topicTitle']);
                $topic->setAttribute('metaKey', $_POST['TestTopics']['metaKey']);
                $topic->setAttribute('metaDescr', $_POST['TestTopics']['metaDescr']);
                $topic->setAttribute('psyTestCategoryId', $_POST['TestTopics']['psyTestCategoryId']);
                $topic->setAttribute('topicDescr', $_POST['TestTopics']['topicDescr']);
                if(is_uploaded_file($_FILES['TestTopics']['tmp_name']['topicImage'])) {
                	$topic->topicImage = CUploadedFile::getInstance($topic, 'topicImage');
                }
                if($topic->save()) {
                	if($topic->topicImage instanceof CUploadedFile) {
                		$tempPath = tempnam(UPLOADS_TEMP, 'ti_');
                		$topic->topicImage->saveAs($tempPath, true);
                		$this->processImage($topic, $tempPath);
                	}
                    Yii::app()->user->setFlash('successMessage', '心理测试主题更新成功。');                	
                } else {
                    Yii::app()->user->setFlash('errorTopic', serialize($topic));
                }
                $this->redirect(array('admin/psytest/edittopic', 'id' => $topic->topicId));
            }
        }
	}
	
	public function processImage($topic, $imagePath) {
		Yii::import('application.extensions.image.Image');
		$image = new Image($imagePath);
		if($image) {
            if($topic->topicImage != '') {
                $origPaths = array();
	    		foreach(TestTopics::suffix2Size() as $suffix => $size) {
		    		$origPaths[] = $topic->getImagePath($suffix);
			    }
            }
			$filename = $topic->generateImageFilename();
			$flag = true;
            // Resize and save
			foreach(TestTopics::suffix2Size() as $suffix => $size) {
				$savePath = $topic->getImagePath($suffix);
                $max = max($size[0], $size[1]);
				$flag = $flag && $image->resize($max, $max, Image::WIDTH)->crop($size[0], $size[1])->save($savePath);
			}
			if($flag) {
                // Delete temporary file
                @unlink($imagePath);
                // Delete old images
                if(isset($origPaths) && count($origPaths) > 0) {
                    foreach($origPaths as $origPath) {
                        @unlink($origPath);
                    }
                }
				return $topic->save();
			} else {
				$topic->topicImage = null;
				return false;
			}
		}
	}

    public function actionEditcategories() {
        $criteria = new CDbCriteria;
		
		$categories = TestCategories::model()->findAll($criteria);
        $_category = new TestCategories;
		$this->render('edit-categories', array(
				'categories' => $categories,
                '_category' => $_category
			)
		);
    }

    public function actionEditcategory() {
        $categoryId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($categoryId !== null) {
            $category = TestCategories::model()->findByPk($categoryId);

            if($category !== null) {
                $this->render('edit-category', array(
                        'category' => $category
                    )
                );
            }
        }
    }

    public function actionDeletecategory() {
        $categoryId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($categoryId) {
            $category = TestCategories::model()->findByPk($categoryId);
			if($category !== null) {
				if($category->delete()) {
                    Yii::app()->user->setFlash('successMessage', '心理测试分类删除成功');
                }
                $this->redirect(array('/admin/psytest/editcategories'));
			}
        }
    }

    public function actionUpdatecategory() {
        if(isset($_POST) && isset($_POST['TestCategories'])) {
            $category = TestCategories::model()->findByPk((int)$_POST['TestCategories']['psyTestCategoryId']);
            if($category !== null) {
                $category->attributes = $_POST['TestCategories'];
                if($category->save()) {
                    Yii::app()->user->setFlash('successMessage', '心理测试分类更新成功。');                	
                } else {
                    Yii::app()->user->setFlash('errorCategory', serialize($category));
                }
                $this->redirect(array('admin/psytest/editcategory', 'id' => $category->psyTestCategoryId));
            }
        }
    }

    public function actionAddcategory() {
        if(isPost() && isset($_POST['TestCategories'])) {
            $category = new TestCategories;
            $category->attributes = $_POST['TestCategories'];
            $category->psyTestCount = 0;

            if($category->save()) {
                Yii::app()->user->setFlash('successMessage', '心理测试分类添加成功。');
                $this->redirect(array('/admin/psytest/editcategory', 'id' => $category->psyTestCategoryId));
            } else {
                Yii::app()->user->setFlash('errorCategory', serialize($category));
                $this->redirect(array('/admin/psytest/editcategories'));
            }
        }
    }
	
	public function actionEditdims() {
		$dims = $this->loadDims();
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/assets/jquery.jeditable.mini.js', CClientScript::POS_HEAD);

		$topic = $this->loadTestTopic();
		$this->render('edit-dims', array('dims' => $dims, '_dim' => new TestDimens, 'topic' => $topic));
	}
	
	public function actionEditsecdims() {
		$secDims = $this->loadSecDims();
		$dims = $this->loadDims();

		$topic = $this->loadTestTopic();
		$this->render('edit-secdims', array('secDims' => $secDims, '_secDim' => new TestSecDims, 'topic' => $topic, 'dims' => $dims));
	}

	public function actionEditquestions() {
		$topic = $this->loadTestTopic();
        if($topic->topicType == TestTopics::TYPE_MARK_SINGLE_CONLUSION || $topic->topicType == TestTopics::TYPE_MARK_MULTI_CONLUSIONS) {
            $questions = $this->loadQuestions();
            Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/assets/jquery.jeditable.mini.js', CClientScript::POS_HEAD);

            $dims = TestDimens::model()->findAllByAttributes(array('topicId' => $topic->topicId));
            $_dims = array();
            foreach($dims as $_dim) {
                $_dims[$_dim->dimensId] = $_dim->dimensDescr;
            }
            $this->render('edit-questions', array('questions' => $questions, 
                    '_dims' => $_dims, 
                    '_mark' => new TestAnswerMark, 
                    '_question' => new TestQuestions,
                    '_answer' => new TestAnswers,
                    'topic' => $topic
                )
            );
        }
	}

    // For linkage type topic
	public function actionEditquestions2() {
        $topic = $this->loadTestTopic();
        if($topic->topicType == TestTopics::TYPE_JUMPING) {
            $questions = $this->loadQuestions();
            $questionsListData = $this->getQuestionsListDataWithOrder($questions);
            $conclusions = $this->loadConclusions();
            Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/assets/jquery.jeditable.mini.js', CClientScript::POS_HEAD);

            $linkType = TestAnswerLinkage::linkType2Text();

            $this->render('edit-linkage-questions', array('questions' => $questions, 
                    '_linkage' => new TestAnswerLinkage, 
                    '_question' => new TestQuestions,
                    '_answer' => new TestAnswers,
                    'topic' => $topic,
                    'questions' => $questions,
                    'linkType' => $linkType,
                    'conclusions' => $conclusions,
                    'questionsListData' => $questionsListData
                )
            );
        }
	}

    public function getQuestionsListDataWithOrder($questions) {
        $listData = array();
        foreach($questions as $question) {
            $listData[$question->questionId] = $question->questionOrder.'. '.$question->question;
        }
        return $listData;
    }
	
	public function actionEditconclusions() {
		$conlcusions = $this->loadConclusions();
		Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/assets/jquery.jeditable.mini.js', CClientScript::POS_HEAD);
		$topic = $this->loadTestTopic();
		
		$this->render('edit-conclusions', array(
				'conclusions' => $conlcusions,
				'_conclusion' => new TestConclusions,
				'topic' => $topic
			)
		);
	}

    public function actionEditconclusion() {
        $conclusionId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($conclusionId !== null) {
            $conclusion = TestConclusions::model()->with('topic')->findByPk($conclusionId);

            $this->render('edit-conclusion', array(
                    'conclusion' => $conclusion
                )
            );
        }
    }
    
    public function actionEditsecdim() {
        $secDimId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($secDimId !== null) {
            $secDim = TestSecDims::model()->with('topic')->findByPk($secDimId);

            $this->render('edit-secdim', array(
                    'secDim' => $secDim
                )
            );
        }
    }
    
    public function actionUpdatesecdim() {
		if(isset($_POST) && isset($_POST['TestSecDims'])) {
            $secDim = TestSecDims::model()->findByPk((int)$_POST['TestSecDims']['secDimId']);
            if($secDim !== null) {
                $secDim->attributes = $_POST['TestSecDims'];
	            // 检查一次维度中是否存在该标识
	            if(TestDimens::model()->find('topicId = '.$secDim->topicId.' AND sku = "'.$secDim->sku.'"') !== null
	            	|| TestSecDims::model()->find('topicId = '.$secDim->topicId.' AND sku = "'.$secDim->sku.'"') !== null) {
	            	$secDim->addError('sku', '该标识在已存在');
	            }
                if( ! $secDim->hasErrors() && $secDim->save()) {
                    Yii::app()->user->setFlash('successMessage', '二次维度更新成功。');
                } else {
                    Yii::app()->user->setFlash('errorDim', serialize($secDim));
                }
                $this->redirect(array('admin/psytest/editsecdim', 'id' => $secDim->secDimId));
            }
        }
    }

    public function actionUpdateconclusion() {
        if(isset($_POST) && isset($_POST['TestConclusions'])) {
            $conclusion = TestConclusions::model()->findByPk((int)$_POST['TestConclusions']['conclusionId']);
            if($conclusion !== null) {
                $conclusion->attributes = $_POST['TestConclusions'];
                $conclusion->updateScenario();
                if($conclusion->save()) {
                    Yii::app()->user->setFlash('successMessage', '结论更新成功。');
                } else {
                    Yii::app()->user->setFlash('errorConclusion', serialize($conclusion));
                }
                $this->redirect(array('admin/psytest/editconclusion', 'id' => $conclusion->conclusionId));
            }
        }
    }

    public function actionAddconclusion() {
        if(isPost() && isset($_POST['TestConclusions'])) {
            $conclusion = new TestConclusions;
            $conclusion->attributes = $_POST['TestConclusions'];
            if(isset($_POST['isGeneralConclusion']) && $_POST['isGeneralConclusion'] == true) {
                $conclusion->conclusionOrder = 0;
                $conclusion->formula = 'true';
            }
            $conclusion->updateScenario();
            if($conclusion->save()) {
                Yii::app()->user->setFlash('successMessage', '结论添加成功。');
            } else {
                Yii::app()->user->setFlash('errorConclusion', serialize($conclusion));
            }
            $this->redirect(array('/admin/psytest/editconclusions', 'id' => $conclusion->topicId, '#' => $conclusion->hasErrors() ? 'add_conclusion' : ''));
        }
    }

    public function actionDeleteconclusion() {
        $conclusionId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($conclusionId) {
            $conclusion = TestConclusions::model()->findByPk($conclusionId);
			if($conclusion !== null) {
				if($conclusion->delete()) {
                    Yii::app()->user->setFlash('successMessage', '结论删除成功');
                }
                $this->redirect(array('/admin/psytest/editconclusions', 'id' => $conclusion->topicId));
			}
        }
    }

    public function actionAddmark() {
        if(isPost() && isset($_POST['TestAnswerMark'])) {
            $mark = new TestAnswerMark;
            $mark->attributes = $_POST['TestAnswerMark'];
            if($mark->save()) {
                Yii::app()->user->setFlash('successMessage', '维度分添加成功。');
            } else {
                Yii::app()->user->setFlash('errorMark', serialize($mark));
            }
            $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($mark->answer->question->topic), 'id' => $mark->answer->question->topic->topicId, '#' => 'answer_lists_'.$mark->answer->answerId));
        }
    }

    public function actionAddlinkage() {
        if(isPost() && isset($_POST['TestAnswerLinkage'])) {
            $linkage = new TestAnswerLinkage;
            $linkage->attributes = $_POST['TestAnswerLinkage'];
            if($linkage->save()) {
                Yii::app()->user->setFlash('successMessage', '跳转目标添加成功。');
            } else {
                Yii::app()->user->setFlash('errorLinkage', serialize($linkage));
            }
            $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($linkage->answer->question->topic), 'id' => $linkage->answer->question->topic->topicId, '#' => 'answer_lists_'.$linkage->answer->answerId));
        }
    }
    
    public function actionAddAnswer() {
        if(isPost() && isset($_POST['TestAnswers'])) {
            $answer = new TestAnswers;
            $answer->attributes = $_POST['TestAnswers'];
            if($answer->save()) {
                Yii::app()->user->setFlash('successMessage', '答案选项添加成功。');
            } else {
                Yii::app()->user->setFlash('errorAnswer', serialize($answer));
            }
            $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($answer->question->topic), 'id' => $answer->question->topic->topicId, '#' => 'question_'.$answer->question->questionId));
        }
    }
    
    public function actionCopyanswers() {
        $fromQuestionId = isset($_GET['from']) ? (int)$_GET['from'] : null;
        $toQuestionId = isset($_GET['to']) ? (int)$_GET['to'] : null;
        
        if($fromQuestionId !== null && $toQuestionId !== null) {
        	$fromQuestion = TestQuestions::model()->with('answers')->findByPk($fromQuestionId);
        	$toQuestion = TestQuestions::model()->with('topic')->findByPk($toQuestionId);
        	
        	if($fromQuestion !== null && $toQuestion !== null) {
        		$flag = true;
        		foreach($fromQuestion->answers as $answer) {
        			$_answer = new TestAnswers;
        			$_answer->questionId = $toQuestion->questionId;
        			$_answer->answer = $answer->answer;
        			$_answer->answerOrder = $answer->answerOrder;
        			$flag = $flag && $_answer->save();
        		}
        		if($flag) {
        			Yii::app()->user->setFlash('successMessage', '成功复制答案。');
        		}
        		$this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($toQuestion->topic), 'id' => $toQuestion->topic->topicId, '#' => 'question_'.$toQuestion->questionId));
        	}
        }
    }
    
    public function getEditQuestionsAction($topic) {
        if($topic->getTypeCatalog() == 'mark') {
            return 'editquestions';
        } else if($topic->getTypeCatalog() == 'jumping') {
            return 'editquestions2';
        }
    }

    public function actionAddquestion() {
        if(isPost() && isset($_POST['TestQuestions'])) {
            $question = new TestQuestions;
            $question->attributes = $_POST['TestQuestions'];
            if($question->save()) {
                Yii::app()->user->setFlash('successMessage', '题目添加成功。');
            } else {
                Yii::app()->user->setFlash('errorQuestion', serialize($question));
            }
            $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($question->topic), 'id' => $question->topic->topicId, '#' => $question->questionId !== null ? 'question_'.$question->questionId : 'add_question'));
        }
    }
    
    public function actionAdddim() {
        if(isPost() && isset($_POST['TestDimens'])) {
            $dim = new TestDimens;
            $dim->attributes = $_POST['TestDimens'];

            if(TestDimens::model()->find('topicId = '.$dim->topicId.' AND sku = "'.$dim->sku.'"') !== null ||
            	TestSecDims::model()->find('topicId = '.$dim->topicId.' AND sku = "'.$dim->sku.'"') !== null) {
            	$dim->addError('sku', '该标识已在维度中存在。');
            }
            if( ! $dim->hasErrors() && $dim->save()) {
                Yii::app()->user->setFlash('successMessage', '维度添加成功。');
            } else {
                Yii::app()->user->setFlash('errorDim', serialize($dim));
            }
            $this->redirect(array('/admin/psytest/editdims', 'id' => $dim->topic->topicId, '#' => $dim->hasErrors() ? 'add_dim' : ''));
        }
    }
    
    public function actionAddsecdim() {
        if(isPost() && isset($_POST['TestSecDims'])) {
            $secDim = new TestSecDims;
            $secDim->attributes = $_POST['TestSecDims'];
            // 检查一次维度中是否存在该标识
            if(TestDimens::model()->find('topicId = '.$secDim->topicId.' AND sku = "'.$secDim->sku.'"') !== null
            	|| TestSecDims::model()->find('topicId = '.$secDim->topicId.' AND sku = "'.$secDim->sku.'"') !== null) {
            	$secDim->addError('sku', '该标识在维度中已存在');
            }
            if( ! $secDim->hasErrors() && $secDim->save()) {
                Yii::app()->user->setFlash('successMessage', '二次维度添加成功。');
            } else {
                Yii::app()->user->setFlash('errorDim', serialize($secDim));
            }
            $this->redirect(array('/admin/psytest/editsecdims', 'id' => $secDim->topic->topicId, '#' => $secDim->hasErrors() ? 'add_dim' : ''));
        }
    }
    
    public function actionDeletesecdim() {
        $secDimId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($secDimId) {
            $secDim = TestSecDims::model()->findByPk($secDimId);
			if($secDim !== null) {
				if($secDim->delete()) {
                    Yii::app()->user->setFlash('successMessage', '二次维度删除成功');
                }
                $this->redirect(array('/admin/psytest/editsecdims', 'id' => $secDim->topic->topicId));
			}
        }
    }

    public function actionDeletedim() {
        $dimId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($dimId) {
            $dim = TestDimens::model()->findByPk($dimId);
			if($dim !== null) {
				if($dim->delete()) {
                    Yii::app()->user->setFlash('successMessage', '维度删除成功');
                }
                $this->redirect(array('/admin/psytest/editdims', 'id' => $dim->topic->topicId));
			}
        }
    }
    
    public function actionDeletetopic() {
        $topicId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($topicId) {
            $topic = TestTopics::model()->findByPk($topicId);
			if($topic !== null) {
				if($topic->delete()) {
                    Yii::app()->user->setFlash('successMessage', '心理测试主题删除成功');
                }
                $this->redirect(array('/admin/psytest'));
			}
        }
    }

    public function actionDeletemark() {
        $markId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($markId) {
            $mark = TestAnswerMark::model()->findByPk($markId);
			if($mark !== null) {
				if($mark->delete()) {
                    Yii::app()->user->setFlash('successMessage', '维度分删除成功');
                }
                $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($mark->answer->question->topic), 'id' => $mark->answer->question->topic->topicId, '#' => 'answer_lists_'.$mark->answer->answerId));
			}
        }
    }

    public function actionDeleteanswer() {
        $answerId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($answerId) {
            $answer = TestAnswers::model()->findByPk($answerId);
			if($answer !== null) {
				if($answer->delete()) {
                    Yii::app()->user->setFlash('successMessage', '答案选项删除成功');
                }
                $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($answer->question->topic), 'id' => $answer->question->topic->topicId, '#' => 'question_'.$answer->question->questionId));
			}
        }
    }
    
    public function actionDeletequestion() {
        $questionId = isset($_GET['id']) ? (int)$_GET['id'] : null;

        if($questionId) {
            $question = TestQuestions::model()->findByPk($questionId);
			if($question !== null) {
				if($question->delete()) {
                    Yii::app()->user->setFlash('successMessage', '题目删除成功');
                }
                $this->redirect(array('/admin/psytest/'.$this->getEditQuestionsAction($question->topic), 'id' => $question->topic->topicId));
			}
        }
    }
    
	public function actionUpdatemark2dim() {
		if(isAjax()) {
			$dimId = isset($_POST['value']) ? (int)$_POST['value'] : null;
			if($dimId !== null) {
				$markId = isset($_POST['id']) ? ($_POST['id']) : null;
				if($markId !== null) {
					$markId = (int)substr($markId, strrpos($markId, '_')+1);
					$mark = TestAnswerMark::model()->with('dim')->findByPk($markId);
					if($markId != '') {
						$mark->dimensId = $dimId;
						if($mark->save()) {
							$mark->refresh();
							echo $mark->dim->dimensDescr;
						}
					} else {
						echo $mark->dim->dimensDescr;
					}
				}
			}
		}
	}
	
    public function actionUpdatelinktype() {
		if(isAjax()) {
			$linkType = isset($_POST['value']) ? (string)$_POST['value'] : null;
			if($linkType !== null) {
				$linkageId = isset($_POST['id']) ? ($_POST['id']) : null;
				if($linkageId !== null) {
					$linkageId = (int)substr($linkageId, strrpos($linkageId, '_')+1);
					$linkage = TestAnswerLinkage::model()->findByPk($linkageId);
					if($linkageId  != '' && in_array($linkType, TestAnswerLinkage::getLinkTypes())) {
                        $linkage->linkType = $linkType;
						if($linkage->save()) {
							echo $linkage->getTypeText();
						}
					} else {
						echo $linkage->getTypeText();
					}
				}
			}
		}
    }

	public function actionUpdatequestion() {
		if(isAjax()) {
			$questionId = isset($_POST['id']) ? $_POST['id'] : null;
			if($questionId !== null) {
				$questionId = (int)substr($questionId, strrpos($questionId, '_')+1);
				$_question = isset($_POST['value']) ? $_POST['value'] : null;
				if($_question) {
					$question = TestQuestions::model()->findByPk($questionId);
					if($_question != '') {
						$question->question = $_question;
						if($question->save()) {
							echo $question->question;
						}
					} else {
						echo $question->question;
					}
				}
			}
		}
	}

	public function actionUpdatequestionorder() {
		if(isAjax()) {
			$questionId = isset($_POST['id']) ? $_POST['id'] : null;
			if($questionId !== null) {
				$questionId = (int)substr($questionId, strrpos($questionId, '_')+1);
				$_questionOrder = isset($_POST['value']) ? $_POST['value'] : null;
				if($_questionOrder) {
					$question = TestQuestions::model()->findByPk($questionId);
					if(is_numeric($_questionOrder)) {
						$question->questionOrder = $_questionOrder;
						if($question->save()) {
							echo $question->questionOrder;
						}
					} else {
						echo $question->questionOrder;
					}
				}
			}
		}
	}

	public function actionUpdatemark() {
		if(isAjax()) {
			$markId = isset($_POST['id']) ? $_POST['id'] : null;
			if($markId !== null) {
				$markId = (int)substr($markId, strrpos($markId, '_')+1);
				$_mark = isset($_POST['value']) ? $_POST['value'] : null;
				if($_mark || $_mark === '0') {
					$mark = TestAnswerMark::model()->findByPk($markId);
					if(is_numeric($_mark)) {
						$mark->mark = $_mark;
						if($mark->save()) {
							echo $mark->mark;
						}
					} else {
						echo $mark->mark;
					}
				}
			}
		}
	}
	
	public function actionUpdateanswer() {
		if(isAjax()) {
			$answerId = isset($_POST['id']) ? $_POST['id'] : null;
			if($answerId !== null) {
				$answerId = (int)substr($answerId, strrpos($answerId, '_')+1);
				$answerText = isset($_POST['value']) ? addslashes($_POST['value']) : null;
				if($answerText !== null) {
					$answer = TestAnswers::model()->findByPk($answerId);
					if($answerText != '') {
						$answer->answer = $answerText;
						if($answer->save()) {
							echo $answer->answer;
						}
					} else {
						echo $answer->answer;
					}
				}
			}
		}
	}
		
	public function actionUpdateanswerorder() {
		if(isAjax()) {
			$answerId = isset($_POST['id']) ? $_POST['id'] : null;
			if($answerId !== null) {
				$answerId = (int)substr($answerId, strrpos($answerId, '_')+1);
				$answerOrder = isset($_POST['value']) ? $_POST['value'] : null;
				if($answerOrder !== null) {
					$answer = TestAnswers::model()->findByPk($answerId);
					if(is_numeric($answerOrder) && $answer) {
						$answer->answerOrder = $answerOrder;
						if($answer->save()) {
							echo $answer->answerOrder;
						}
					} else {
						echo $answer->answerOrder;
					}
				}
			}
		}
	}
		
	public function actionUpdatedim() {
		if(isAjax()) {
			$dimId = isset($_POST['id']) ? $_POST['id'] : null;
			if($dimId !== null) {
				$dimId = (int)substr($dimId, strrpos($dimId, '_')+1);
				$dimDescr = isset($_POST['value']) ? addslashes($_POST['value']) : null;
				if($dimDescr !== null) {
					$dim = TestDimens::model()->findByPk($dimId);
					if($dimDescr != '') {
						$dim->dimensDescr = $dimDescr;
						if($dim->save()) {
							echo $dim->dimensDescr;
						}
					} else {
						echo $dim->dimensDescr;
					}
				}
			}
		}
	}
	
	public function loadConclusions($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$conclusions = TestConclusions::model()->findAllByAttributes(array('topicId' => $id !== null ? $id : (int)$_GET['id']));
		}
		
		if($conclusions === null) {
			throw new CHttpException(404, 'The requested questions does not exist.');
		}
		return $conclusions;
	}
	
	public function loadQuestions($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$questions = TestQuestions::model()->with('answers', 'answers.mark', 'answers.mark.dim')->findAllByAttributes(array('topicId' => $id !== null ? $id : (int)$_GET['id']));
		}
		
		if($questions === null) {
			throw new CHttpException(404, 'The requested questions does not exist.');
		}
		return $questions;
	}
	
	public function loadDims($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$dims = TestDimens::model()->findAllByAttributes(array('topicId' => $id !== null ? $id : (int)$_GET['id']));
		}
		
		if($dims === null) {
			throw new CHttpException(404, 'The requested dims does not exist.');
		}
		return $dims;
	}
	
	public function loadSecDims($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$secDims = TestSecDims::model()->findAllByAttributes(array('topicId' => $id !== null ? $id : (int)$_GET['id']));
		}
		
		if($secDims === null) {
			throw new CHttpException(404, 'The requested dims does not exist.');
		}
		return $secDims;
	}
	
	public function loadTestTopic($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$topic = TestTopics::model()->findbyPk($id !== null ? $id : (int)$_GET['id']);
		}
		
		if($topic === null) {
			throw new CHttpException(404, 'The requested psytest does not exist.');
		}
		return $topic;
	}
}
